/**
 * KE私人专用库
 */

export default {
    install(Vue: any) {
        Vue.prototype.$validator = function (form: string) {
            return this.$refs[form].validate();
        };

        Vue.prototype.$clearValidator = function (form: string) {
            return this.$refs[form].clearValidate();
        };

        Vue.prototype.$array = {
            update(list: any[], key: any, data: any, pk: string = 'id') {
                const index = list.findIndex((_) => _[pk] == key);
                if (index >= -1) {
                    list.splice(index, 1, { ...list[index], ...data });
                }
            },
            delete(list: any[], key: any, pk: string = 'id') {
                const index = list.findIndex((_) => _[pk] == key);
                if (index >= -1) {
                    list.splice(index, 1);
                }
            },
            tree(list: any[], id: string = 'id', pid: string = 'pid', children: string = 'children') {
                let arr: any = JSON.parse(JSON.stringify(list));
                let map: any = {};
                for (let i = 0; i < arr.length; i++) {
                    (map[arr[i][id]] as any) = arr[i]
                }
                let newArray: any = [];
                const f = () => {
                    for (let i = 0; i < arr.length; i++) {
                        let parent = map[arr[i][pid]];
                        if (parent) {
                            (parent[children] || (parent[children] = [])).push(arr[i])
                        } else {
                            newArray.push(arr[i])
                        }
                    }
                };
                f();
                return newArray
            },
        };
    }
}
